package com.telit.firecommand.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.telit.android.feign.RemoteAndroidService;
import com.telit.common.constant.MsgConstants;
import com.telit.common.constant.MsgIdentificationConstants;
import com.telit.common.constant.NoticeTypeConstants;
import com.telit.common.entity.AppTask;
import com.telit.common.entity.DataReturn;
import com.telit.common.pojo.AliPushContentPojo;
import com.telit.common.pojo.AliPushMessagePojo;
import com.telit.common.util.AliyunPushMessageUtils;
import com.telit.common.util.MediaUrlUtils;
import com.telit.communicate.dto.SendMessageDTO;
import com.telit.communicate.feign.RemoteCommunicateService;
import com.telit.firecommand.dao.AppTaskFeedbackDao;
import com.telit.firecommand.dao.CommFireAlarmDao;
import com.telit.firecommand.dto.AppTaskFeedbackDto;
import com.telit.firecommand.entity.AppTaskFeedback;
import com.telit.firecommand.entity.CommFireAlarm;
import com.telit.firecommand.entity.FileUploadLog;
import com.telit.firecommand.service.FileUploadLogService;
import com.telit.firecommand.service.FireAdminService;
import com.telit.firecommand.service.TaskFeedBackService;
import com.telit.firecommand.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author chencf
 * @description 任务反馈实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TaskFeedBackServiceImpl implements TaskFeedBackService {

    @Autowired
    private AppTaskFeedbackDao appTaskFeedbackDao;

    @Autowired
    private RemoteCommunicateService communicateFeignClient;

    @Autowired
    private FileUploadLogService fileUploadLogService;

    @Autowired
    private CommFireAlarmDao commFireAlarmDao;

//    @Autowired
//    private FireQueryService fireQueryService;
//
//    @Autowired
//    private WebSocketPushMsgLogService webSocketPushMsgLogService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RemoteAndroidService androidFeignClient;

    @Autowired
    private FireAdminService fireAdminService;

//    @Autowired
//    private MsgCenterService msgCenterService;


    @Override
    public int addTaskFeedback(AppTaskFeedback appTaskFeedback, List<MultipartFile> files) {
        // 查询反馈表中是否存在该记录,存在就删除
//        AppTaskFeedback oldAppTaskFeedback = selectByTaskIdAndUserId(appTaskFeedback.getTaskId(),appTaskFeedback.getFeedbackPersonId());
//        if(oldAppTaskFeedback != null){
//            appTaskFeedbackDao.deleteById(oldAppTaskFeedback.getId());
//        }

        // 新增文件上传表数据
        if (!CollectionUtils.isEmpty(files)) {
            List<String> mediaImgList = new ArrayList<>();
            // 2.1获取任务关于火情的信息,eventType=1是火情任务
            CommFireAlarm commFireAlarm = commFireAlarmDao.selectByTaskId(appTaskFeedback.getTaskId(), "1",
                    appTaskFeedback.getFeedbackPersonId());
            files.forEach(file -> {
                // 封装数据
                FileUploadLog fileUploadLog = new FileUploadLog();
                fileUploadLog.setUploadTime(new Date());

                //TODO:v1.1.0
//                String path = MinioUtils.upload(file, MinioConstants.BUCKET_FORESTRY_NAME,
//                        MinioConstants.BUCKET_FIRECOMMAND_SUFFIX_NAME);
                String path = null;
                fileUploadLog.setFilePath(path);
                fileUploadLog.setFileName(file.getOriginalFilename());
                fileUploadLog.setUploader(appTaskFeedback.getFeedbackPersonName());
                fileUploadLog.setFireId(commFireAlarm == null ? null : commFireAlarm.getId());
                //fileUploadLog.setAlarmResource(commFireAlarm == null? null:commFireAlarm.getResource());
                fileUploadLogService.add(fileUploadLog);

                // 添加集合，新增进反馈表中
                mediaImgList.add(path);
            });
            appTaskFeedback.setMediaUrl(JSONObject.toJSONString(mediaImgList));
        }

        // 新增任务反馈记录
        appTaskFeedback.setFeedbackTime(new Date());
        int count = appTaskFeedbackDao.insert(appTaskFeedback);

        //根据任务ID查询任务类型，如果3或者9表示为火情核实任务，需要发送web通知和app通知
        DataReturn dataReturn = androidFeignClient.findById(appTaskFeedback.getTaskId());
        AppTask appTask = null;
        if (dataReturn.getData() != null) {
            appTask = JSON.parseObject(JSON.toJSONString(dataReturn.getData()), AppTask.class);
        }

        //如果是“3”为火情核实巡护任务，“9”为火情核实巡航任务
        if (appTask != null && ("3".equals(appTask.getType()) || "9".equals(appTask.getType()))) {
            //查找任务下发人的ID
            Long taskCreatePersonId = appTask.getCreatePersonId();
            if (taskCreatePersonId != null && taskCreatePersonId != 0) {
                //推送消息到web端
                SendMessageDTO sendMessageDTO = new SendMessageDTO();
                //推送给下发任务的人
                sendMessageDTO.setFlag("special");
                sendMessageDTO.setUserId(Convert.toStrArray(taskCreatePersonId));
                sendMessageDTO.setMsg(
                        JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_VERIFICATION_FEEDBACK, null)));
                communicateFeignClient.sendMsg(sendMessageDTO);
                //推送给所有web端
              /*  sendMessageDTO.setFlag("web");
                sendMessageDTO.setMsg(JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_VERIFICATION_FEEDBACK, null)));
                communicateFeignClient.sendMsg(sendMessageDTO);*/

                /*//推送到APP通知给防火管理员,由于需要推送到下发任务人员，此方法暂时作废
                List<String> fireMangerIdList = fireAdminService.fireMangerIdList();
                List<Long> convertFireManagerIdList=new ArrayList<>();
                if(fireMangerIdList !=null && fireMangerIdList.size()>0){
                    convertFireManagerIdList = fireMangerIdList.stream().map(fireManagerId -> Long.parseLong(fireManagerId.trim())).collect(Collectors.toList());
                }*/


                String fireMangerIdStrList = String.valueOf(taskCreatePersonId);
                List<Long> taskCreatePersonIdList = Convert.toList(Long.class, taskCreatePersonId);
                List<String> taskCreatePersonStrIdList = Convert.toList(String.class, fireMangerIdStrList);
//                SysUserDetailVo userInfo = userInfoService.getUserInfo(appTaskFeedback.getFeedbackPersonId());
//                String realName = "";
//                if (userInfo != null) {
//                    realName = userInfo.getRealName();
//                }
                String content = null;
                String title = "你有新的任务反馈";
//                if ("3".equals(appTask.getType())) {
//                    content = "护林员" + realName + "对火情核实巡护任务进行了任务反馈，请前往查看";
//                    msgCenterService.addBatch(new CommMsgCenterLogDTO(content, "1", new Date(), "1", realName, title, taskCreatePersonIdList));
//                }
//                if ("9".equals(appTask.getType())) {
//                    content = "飞手" + realName + "对火情核实巡护任务进行了任务反馈，请前往查看";
//                    msgCenterService.addBatch(new CommMsgCenterLogDTO(content, "2", new Date(), "1", realName, title, taskCreatePersonIdList));
//                }
//            String title = "你有新的任务反馈";

                try {
                    if (appTaskFeedback.getFireType() != null && appTaskFeedback.getFireType() == 0) {
                        AliyunPushMessageUtils.customizeAdvancedPush(
                                new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE,
                                        MsgConstants.DEVICE_TYPE_ANDROID, title, taskCreatePersonStrIdList,
                                        new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_WRONG_FEEDBACK,
                                                JSON.toJSONString(content))));
                    } else {
                        AliyunPushMessageUtils.customizeAdvancedPush(
                                new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE,
                                        MsgConstants.DEVICE_TYPE_ANDROID, title, taskCreatePersonStrIdList,
                                        new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_NORMAL,
                                                JSON.toJSONString(content))));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
            }

            /*fireMangerIdList.forEach(e -> {
                CommMsgCenterLog log = new CommMsgCenterLog(content, "4", new Date(), "1", commFireAlarm.getFinderName(), title, Long.parseLong(e));
                commMsgCenterLogDao.insert(log);
            });*/
        }

        return count;
    }

    @Override
    public AppTaskFeedback detail(Long id) {
        AppTaskFeedback appTaskFeedback = appTaskFeedbackDao.selectById(id);
        if (appTaskFeedback != null && StringUtils.hasText(appTaskFeedback.getMediaUrl())) {
            appTaskFeedback.setMediaUrlList(MediaUrlUtils.handleMediaUrlToList(appTaskFeedback.getMediaUrl()));
        }
        return appTaskFeedback;
    }

    @Override
    public List<AppTaskFeedbackDto> queryUnReadTaskFeedBack(Long userId) {
//        List<AppTaskFeedback> list=appTaskFeedbackDao.queryTaskFeedBackByUserId(userId);
//        /*//根据用户ID查询与该用户在同一行政区划下的火情核实巡航/巡护未读任务，暂时作废
//        SysUserDetailVo sysUserVo = userInfoService.getUserInfo(userId);
//        List<AppTaskFeedback> list=appTaskFeedbackDao.queryTaskFeedBackBydistrictCode(sysUserVo.getDeptRegionCode());*/
////        List<AppTaskFeedback> list=appTaskFeedbackDao.queryTaskFeedBackBydistrictCode("320111009010");
//        List<Long> hasReadTaskFeedbackIds = webSocketPushMsgLogService.queryHasReadMsg(2, userId);
//        if(CollectionUtil.isNotEmpty(list)){
//            List<AppTaskFeedback> filterAppTaskFeedbackList = list.stream().filter(e -> !hasReadTaskFeedbackIds.contains(e.getId())).collect(Collectors.toList());
//            //判断任务反馈集合是否为空，如果为空，直接返回
//            if(CollectionUtil.isEmpty(filterAppTaskFeedbackList)){
//                return null;
//            }
//            //任务反馈返回对象集合
//            List<AppTaskFeedbackDto> appTaskFeedbackDtoList = new ArrayList<>();
//            //创建任务ID集合
//            List<Long> taskIdList=new ArrayList<>();
//            filterAppTaskFeedbackList.forEach(e -> {
//                Long fireId = e.getFireId();
//                CommFireAlarm commFireAlarm = fireQueryService.queryById(fireId);
//                if (commFireAlarm != null) {
//                    e.setReportTime(commFireAlarm.getFindTime());
//                    e.setDistrictName(commFireAlarm.getDistrictName());
//                    e.setDetailAddress(commFireAlarm.getDetailAddress());
//                    e.setLongitude(commFireAlarm.getLongitude());
//                    e.setLatitude(commFireAlarm.getLatitude());
//                    e.setReportResource(commFireAlarm.getResource());
//                    e.setSourceName(commFireAlarm.getSourceName());
//                }
//                //新建返回实体
//                AppTaskFeedbackDto appTaskFeedbackDto = new AppTaskFeedbackDto();
//                //把当前实体复制到返回实体
//                BeanUtil.copyProperties(e, appTaskFeedbackDto);
//                //转换时间类型
//                if (e.getFeedbackTime() != null) {
//                    appTaskFeedbackDto.setFeedbackTime(DateUtil.format(e.getFeedbackTime(), "yyyy-MM-dd HH:mm"));
//                }
//                if (e.getAssignTaskTime() != null) {
//                    appTaskFeedbackDto.setAssignTaskTime(DateUtil.format(e.getAssignTaskTime(), "yyyy-MM-dd HH:mm"));
//                }
//                if (e.getReportTime() != null) {
//                    appTaskFeedbackDto.setReportTime(DateUtil.format(e.getReportTime(), "yyyy-MM-dd HH:mm"));
//                }
//                appTaskFeedbackDtoList.add(appTaskFeedbackDto);
//                //添加任务ID到任务ID集合中
//                taskIdList.add(appTaskFeedbackDto.getTaskId());
//            });
//            //通过任务ID获取任务类型
//            DataReturn appTaskDataReturn = androidFeignClient.findTyeByIds(taskIdList);
//            //当返回值不为空转换成map
//            if (appTaskDataReturn.getData() != null) {
//                Map<Long,String> appTaskTypeByIds= (Map<Long, String>) appTaskDataReturn.getData();
//                //遍历返回值对象，获取对象，设置任务类型
//                appTaskFeedbackDtoList.forEach(appTaskFeedbackDto -> {
//                    appTaskFeedbackDto.setTaskType(appTaskTypeByIds.get(appTaskFeedbackDto.getTaskId()));
//                });
//            }
//        }
        return null;
       /* 此部分代码存在雍余，换成以上代码
       if(CollectionUtil.isNotEmpty(list)) {
            List<AppTaskFeedbackDto> appTaskFeedbackDtoList = new ArrayList<>();
            list.forEach(e -> {
                Long fireId = e.getFireId();
                CommFireAlarm commFireAlarm = fireQueryService.queryById(fireId);
                if (commFireAlarm != null) {
                    e.setReportTime(commFireAlarm.getFindTime());
                    e.setDistrictName(commFireAlarm.getDistrictName());
                    e.setDetailAddress(commFireAlarm.getDetailAddress());
                    e.setLongitude(commFireAlarm.getLongitude());
                    e.setLatitude(commFireAlarm.getLatitude());
                    e.setReportResource(commFireAlarm.getResource());
                    e.setSourceName(commFireAlarm.getSourceName());
                }
                //新建返回实体
                AppTaskFeedbackDto appTaskFeedbackDto = new AppTaskFeedbackDto();
                //把当前实体复制到返回实体
                BeanUtil.copyProperties(e, appTaskFeedbackDto);
                //转换时间类型
                if (e.getFeedbackTime() != null) {
                    appTaskFeedbackDto.setFeedbackTime(DateUtil.format(e.getFeedbackTime(), "yyyy-MM-dd HH:mm"));
                }
                if (e.getAssignTaskTime() != null) {
                    appTaskFeedbackDto.setAssignTaskTime(DateUtil.format(e.getAssignTaskTime(), "yyyy-MM-dd HH:mm"));
                }
                if (e.getReportTime() != null) {
                    appTaskFeedbackDto.setReportTime(DateUtil.format(e.getReportTime(), "yyyy-MM-dd HH:mm"));
                }
                //通过任务ID获取任务类型,此部分远程调用andriod次数会随着
                DataReturn appTaskDataReturn = androidFeignClient.findById(e.getTaskId());
                if (appTaskDataReturn.getData() != null) {
                    AppTask appTask = JSON.parseObject(JSON.toJSONString(appTaskDataReturn.getData()), AppTask.class);
                    appTaskFeedbackDto.setTaskType(appTask.getType());
                }
                appTaskFeedbackDtoList.add(appTaskFeedbackDto);
            });
            List<Long> hasReadTaskFeedbackIds = webSocketPushMsgLogService.queryHasReadMsg(2, userId);
//        return appTaskFeedbackDtoList;
            return appTaskFeedbackDtoList.stream().filter(e -> !hasReadTaskFeedbackIds.contains(e.getId())).collect(Collectors.toList());
        }
        return null;*/
    }

    @Override
    public Boolean queryHasUnReadTaskFeedBack(Long userId) {
//        SysUserDetailVo sysUserVo = userInfoService.getUserInfo(userId);
//        List<AppTaskFeedback> list=appTaskFeedbackDao.queryTaskFeedBackBydistrictCode(sysUserVo.getDeptRegionCode());
//        List<Long> hasReadTaskFeedbackIds = webSocketPushMsgLogService.queryHasReadMsg(2, userId);
//        return list.stream().filter(e->!hasReadTaskFeedbackIds.contains(e.getId())).collect(Collectors.toList()).size()>0;
        return true;
    }

    /**
     * 查询是否有反馈记录
     *
     * @return
     */
    private AppTaskFeedback selectByTaskIdAndUserId(Long taskId, Long userId) {
        QueryWrapper<AppTaskFeedback> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", taskId);
        wrapper.eq("feedback_person_id", userId);
        return appTaskFeedbackDao.selectOne(wrapper);
    }

}
